<?php
/* 
 * Author: Quan Van Sinh
 * Email: sinhvnb@vietnambiz.com
 */
function getAllArticle($limit,$status='') {
    global $DB,$config;

    if($_GET['searchArticleSubmit']=='Search' AND $_GET['articleActionType']=='searchArticle') {
        $keyword    = $_GET['searchKeyword'];
        $dateFrom   = $_GET['dateFrom'];
        $dateTo     = $_GET['dateTo'];
        $catId      = $_GET['categoryId'];

        if(isset($_SESSION['articlePageEdit'])) {
            $config['page'] = $_SESSION['articlePageEdit'];
        }

        if(intval($catId)>0) {
            $catTree = get_cat_tree($catId);
            foreach($catTree as $k=>$rs) {
                $cat_id_string .= $rs['id'].',';
            }
            if($cat_id_string!='') {
                $cat_id_string = substr($cat_id_string, 0, -1);
            }else {
                $cat_id_string = $catId;
            }

        }

        $condition = "";
        if($keyword!='') {
            $condition = " WHERE (a.title LIKE '%".filter($keyword)."%' OR a.description LIKE '%".filter($keyword)."%') ";
            if($dateFrom!='' AND $dateTo!='') {
                $condition .= " AND (a.create_date >='$dateFrom' AND a.create_date <='$dateTo') ";
            }
            if(intval($catId)>0) {
                $condition .= " AND (a.cat_id=".intval($catId)." OR a.cat_id IN ($cat_id_string) ) ";
            }
        }else {
            if($dateFrom!='' AND $dateTo!='') {
                $condition .= " WHERE (a.create_date >='$dateFrom' AND a.create_date <='$dateTo') ";
                if($catId!='') {
                    $condition .= " AND (a.cat_id=".intval($catId)." OR a.cat_id IN ($cat_id_string) ) ";
                }
            }else {
                if(intval($catId)>0) {
                    $condition .= " WHERE (a.cat_id=".intval($catId)." OR a.cat_id IN ($cat_id_string) ) ";
                }
            }
        }

        if(isset($_SESSION['articleStatusFilter']) AND $_SESSION['articleStatusFilter']!='') {
            if($condition!='') {
                $status = " AND a.status='".filter($_SESSION['articleStatusFilter'])."' ";
            }else {
                $status = " WHERE a.status='".filter($_SESSION['articleStatusFilter'])."' ";
            }

            $condition .= $status;
        }

        $sqlTotalRows="SELECT * FROM article a".$condition;
        $totalRows =  $DB->num_rows($DB->query($sqlTotalRows));

        $totalPages = ceil($totalRows/$config ['total_article_on_admin']);
        $start = (($config ['page']*$config ['total_article_on_admin'])-$config ['total_article_on_admin']);
        $sql="SELECT a.*,c.name as category_name FROM article a LEFT JOIN article_category c ON a.cat_id=c.id ".$condition." ORDER BY create_date DESC LIMIT $start,$limit";
        $rsAllArticle = $DB->query($sql);
    }else {
        if(isset($_SESSION['articleStatusFilter']) AND $_SESSION['articleStatusFilter']!='') {
            $status = " WHERE a.status='".filter($_SESSION['articleStatusFilter'])."' ";
        }

        $sqlTotalRows="SELECT * FROM article a".$status;
        $totalRows =  $DB->num_rows($DB->query($sqlTotalRows));


        $totalPages = ceil($totalRows/$config ['total_article_on_admin']);
        $start = (($config ['page']*$config ['total_article_on_admin'])-$config ['total_article_on_admin']);
        $sql="SELECT a.*,c.name as category_name FROM article a LEFT JOIN article_category c ON a.cat_id=c.id ".$status." ORDER BY create_date DESC LIMIT $start,$limit";
        $rsAllArticle = $DB->query($sql);
    }
    return Array("rs"=>$rsAllArticle,"totalRows"=>$totalRows);

}

function checkArticleExist($articlename) {
    global $DB;
    $sql="SELECT * FROM article WHERE articlename='".mysql_escape_string($articlename)."'";
    $rsArticle = $DB->query_first($sql);
    if($rsArticle['articlename']!='$articlename') {
        return FALSE;
    }else {
        return TRUE;
    }
}

function articleAction() {
    global $config;
    if(isset($_REQUEST['articleActionType'])) {
        $actionType = $_REQUEST['articleActionType'];
        switch ($actionType) {
            case 'addArticle':
                addArticle();
                break;
            case 'viewAddArticle':
                break;
            case 'editArticle':
                break;
            case 'updateArticle':
                if(isset($_POST['id'])) {
                    updateArticle($_POST['id']);
                }else {
                    getAllArticle($config ['total_article_on_admin']);
                }
                break;
            case 'updateFrontPageDate':
                if(isset($_POST['id'])) {
                    updateArticleFrontPageDate($_POST['id']);
                }else {
                    getAllArticle($config ['total_article_on_admin']);
                }
                break;
            case 'deleteArticle':
                if(isset($_POST['id'])) {
                    deleteArticle($_POST['id']);
                }else {
                    getAllArticle($config ['total_article_on_admin']);
                }
                break;
            case 'actionMultil':
                if(isset($_POST['multiArticleId'])) {
                    actionMultil();
                }else {
                    $_SESSION['rsMessages'] = '<span class="error">Please select the articles to perform action!</span>';
                    getAllArticle($config ['total_article_on_admin']);
                }
                break;
            default:
                getAllArticle($config ['total_article_on_admin']);
        }
    }
}

function actionMultil() {
    global $DB,$config;
    $ids = $_POST['multiArticleId'];
    switch ($_POST['action']) {
        case 'delete':
            for($i=0;$i<count($ids);$i++) {
                deleteArticle(intval($ids[$i]),'multi');
            }
            $_SESSION['rsMessages'] = '<span class="success">Delete the articles successfull!</span>';
            break;
        case 'yes':
            for($i=0;$i<count($ids);$i++) {
                $DB->query("UPDATE article set status='yes' WHERE id=".intval($ids[$i]));
            }
            $_SESSION['rsMessages'] = '<span class="success">Change status to yes successfull!</span>';
            break;
        case 'pending':
            for($i=0;$i<count($ids);$i++) {
                $DB->query("UPDATE article set status='pending' WHERE id=".intval($ids[$i]));
            }
            $_SESSION['rsMessages'] = '<span class="success">Change status to pending successfull!</span>';
            break;
        case 'no':
            for($i=0;$i<count($ids);$i++) {
                $DB->query("UPDATE article set status='no' WHERE id=".intval($ids[$i]));
            }
            $_SESSION['rsMessages'] = '<span class="success">Change status to no successfull!</span>';
            break;
        default:
            getAllArticle($config ['total_house_on_article_admin']);
    }
}

function addArticle() {
    global $DB,$config;
    $upload_dir = $config ['upload_dir'].'/article_attachs/'.date("Y").'/'.date("m");
    $upload_dir_attach_insert = '/article_attachs/'.date("Y").'/'.date("m");
    $title = $_POST['title'];
    $link = CleanFileName(filter($_POST['title'])).'-'.rand(0,999);
    $cat_id = intval($_POST['categoryId']);
    $image = filter($_POST['image']);
    $short_description = $_POST['short_description'];
    $description = $_POST['description'];
    $status = filter($_POST['status']);
    $front_page = filter($_POST['front_page']);
    $create_date = $_POST['createDate'];
    $tags = $_POST['keyword'];
    $attachs = $_FILES['attachs'];
    $now = time();

    //insert data to article table
    if($create_date=='') {
        $create_date = date('Y-m-d H:i:s');
    }

    $addArticleSql = "INSERT INTO article (cat_id,title,link,short_description,description,image,user_id,create_date,front_page,front_page_date,status)
                            VALUES
                          ($cat_id,'$title','$link','$short_description','$description','$image',".$_SESSION['userid'].",'$create_date','$front_page','$create_date','$status')";
    $DB->query($addArticleSql);
    $articleId = mysql_insert_id();

    //insert data to tags
    for($i=0;$i<count($tags);$i++) {
        if($tags[$i]!='') {
            $tempTags = checkTagExist($tags[$i]);
            if($tempTags=='donthave') {//chua ton` tai tag nay nen insert vao database
                $tags_link = CleanFileName(filter($tags[$i]));
                $DB->query("INSERT INTO tags (tags, tags_link) VALUES ('$tags[$i]', '$tags_link')");
                $DB->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($articleId,".mysql_insert_id().")");
            }else {//ton tai rui nen lay id (chinh la $tempTags)
                $DB->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($articleId,$tempTags)");
            }
        }
    }

    //insert attachs
    if(count($attachs['name'])>0) {
        for($i=0;$i<count($attachs['name']);$i++) {
            $arrAttachsNameExplode = explode('.', $attachs["name"][$i]);
            $attachsExtention = $arrAttachsNameExplode[(count($arrAttachsNameExplode)-1)];
            $realFileName = $attachs["name"][$i];
            $filename = $now.'-'.rand(0,999999).'.'.strtolower($attachsExtention);
            $filesize = $attachs["size"][$i];
            if (!file_exists($upload_dir)) {
                if(!mkdir($upload_dir, 0777,true)) {
                    $_SESSION['rsMessages'] .= "<span class='error'>Can not create directory, please check permission.</span><br/>";
                }
            }
            if (move_uploaded_file($attachs["tmp_name"][$i],$upload_dir."/".$filename)) {
                $DB->query("INSERT INTO article_attach (article_id,real_filename,filename,filesize,create_date) VALUES ($articleId,'$realFileName','$upload_dir_attach_insert/$filename','$filesize','$create_date')");
            }
        }
    }

    $_SESSION['rsMessages'] = "<span class='success'>Add new article successfull!</span>";
}

function checkTagExist($tag) {
    global $DB;
    $rs = $DB->query_first("SELECT id FROM tags WHERE tags='$tag'");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function checkArticleTagExist($article_id,$tag_id) {
    global $DB;
    $rs = $DB->query_first("SELECT id FROM article_tags WHERE article_id=$article_id AND tag_id=$tag_id");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function editArticle($id) {
    global $DB;
    $editArticleSql = "SELECT * FROM article WHERE id = ".intval($id);
    $rsArticle = $DB->query_first($editArticleSql);

    $tagSQL = "SELECT t.* FROM article_tags at LEFT JOIN tags t ON at.tag_id=t.id WHERE at.article_id=".intval($id);
    $rsTags = $DB->query($tagSQL);
    return array(   'rsArticle'     =>$rsArticle, 'rsTags' => $rsTags);
}


function updateArticle($id) {
    global $DB,$config;
    $upload_dir = $config ['upload_dir'].'/article_attachs/'.date("Y").'/'.date("m");
    $upload_dir_attach_insert = '/article_attachs/'.date("Y").'/'.date("m");
    $id = intval($id);
    $title = $_POST['title'];
    //$link = CleanFileName(filter($_POST['title'])).'-'.rand(0,999);
    $cat_id = intval($_POST['categoryId']);
    $image = filter($_POST['image']);
    $short_description = $_POST['short_description'];
    $description = $_POST['description'];
    $status = filter($_POST['status']);
    $front_page = filter($_POST['front_page']);
    $tags = $_POST['keyword'];
    $createDate = $_POST['createDate'];
    $removedTags = explode(',', $_POST['removedTags']);
    $removeAttachs = $_POST['removeAttachs'];
    $attachs = $_FILES['attachs'];
    $now = time();
    if($createDate!='') {
        $updateArticleSql = "UPDATE article SET cat_id=$cat_id,
                        title='$title', image='$image', short_description='$short_description', description='$description', front_page='$front_page', create_date='$createDate', status='$status'
                        WHERE id = ".$id;
    }else {
        $updateArticleSql = "UPDATE article SET cat_id=$cat_id,
                        title='$title', image='$image', short_description='$short_description', description='$description', front_page='$front_page', status='$status'
                        WHERE id = ".$id;
    }

    if($id!=0) {
        $DB->query($updateArticleSql);//update article table
        //delete tag had been removed
        for($i=0;$i<count($removedTags);$i++) {
            if($removedTags[$i]!='') {
                $rsRemoveTagId = $DB->query_first("SELECT id FROM tags WHERE tags='".$removedTags[$i]."'");
                if($rsRemoveTagId['id']!=0) {
                    $DB->query("DELETE FROM article_tags WHERE id = ".$rsRemoveTagId['id']);
                }
            }
        }
        //insert data to tags table
        for($i=0;$i<count($tags);$i++) {
            if($tags[$i]!='') {
                $tempTags = checkTagExist($tags[$i]);
                if($tempTags=='donthave') {//chua ton` tai tag nay nen insert vao database
                    $DB->query("INSERT INTO tags (tags) VALUES ('$tags[$i]')");
                    $DB->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($id,".mysql_insert_id().")");
                }else {//ton tai rui nen lay id (chinh la $tempTags)
                    if(checkArticleTagExist($id,$tempTags)=='donthave') {
                        $DB->query("INSERT INTO article_tags (article_id,tag_id) VALUES ($id,$tempTags)");
                    }
                }
            }
        }

        //remove attachs file
        if(count($removeAttachs)>0) {
            for($i=0;$i<count($removeAttachs);$i++) {
                $deleteAttachFileSql = "SELECT filename FROM article_attach WHERE id = ".intval($removeAttachs[$i]);
                $rsDeleteAttach = $DB->query_first($deleteAttachFileSql);
                $filenameDelete = $config ['upload_dir'].$rsDeleteAttach['filename'];
                if(unlink($filenameDelete)) {
                    $DB->query("DELETE FROM article_attach WHERE id = ".intval($removeAttachs[$i]));
                }
            }
        }

        //insert attachs

        for($i=0;$i<count($attachs['name']);$i++) {
            $arrAttachsNameExplode = explode('.', $attachs["name"][$i]);
            $attachsExtention = $arrAttachsNameExplode[(count($arrAttachsNameExplode)-1)];
            $realFileName = $attachs["name"][$i];
            $filename = $now.'-'.rand(0,999999).'.'.strtolower($attachsExtention);
            $filesize = $attachs["size"][$i];
            if (!file_exists($upload_dir)) {
                if(!mkdir($upload_dir, 0777,true)) {
                    $_SESSION['rsMessages'] .= "<span class='error'>Can not create directory, please check permission.</span><br/>";
                }
            }
            if (move_uploaded_file($attachs["tmp_name"][$i],$upload_dir."/".$filename)) {
                $create_date = date('Y-m-d H:i:s');
                $DB->query("INSERT INTO article_attach (article_id,real_filename,filename,filesize,create_date) VALUES ($id,'$realFileName','$upload_dir_attach_insert/$filename','$filesize','$create_date')");   
            }
        }
        
    }


}

function getArticleAttachs($id) {
    global $DB;
    $sql = "SELECT * FROM article_attach WHERE article_id = ".intval($id);
    $rs = $DB->query($sql);
    return $rs;
}

function updateArticleFrontPageDate($id) {
    global $DB;
    $rsCheck = $DB->query_first("SELECT front_page FROM article WHERE id=".intval($id));
    if($rsCheck['front_page']=='yes') {
        $DB->query_first("UPDATE article SET front_page='no' WHERE id=".intval($id));
        echo 'no';die;
    }elseif($rsCheck['front_page']=='no') {
        $create_date = date('Y-m-d H:i:s');
        $DB->query_first("UPDATE article SET front_page='yes', front_page_date='$create_date', status='yes' WHERE id=".intval($id));
        echo 'yes';die;
    }else {
        echo 'hack';die;
    }
}

function deleteArticle($id,$multi='') {
    global $DB;global $config;
    if($multi=='') {
        $deleteArticleSql = "DELETE FROM article WHERE id = ".intval($id);
        $DB->query($deleteArticleSql);

        $deleteArticleTagsSql = "DELETE FROM article_tags WHERE article_id = ".intval($id);
        $DB->query($deleteArticleTagsSql);

        $_SESSION['rsMessages'] = "<span class='success'>Delete article successfull!</span>";
        die;
    }else {
        $deleteArticleSql = "DELETE FROM article WHERE id = ".intval($id);
        $DB->query($deleteArticleSql);
        $deleteArticleTagsSql = "DELETE FROM article_tags WHERE article_id = ".intval($id);
        $DB->query($deleteArticleTagsSql);
        $_SESSION['rsMessages'] = "<span class='success'>Delete article successfull!</span>";
    }

}

function get_cat_tree($parent_id = 0,$space = ' ', $trees = NULL) {
    if(!$trees) $trees = array();
    $sql = mysql_query("SELECT * FROM article_category WHERE  parent_id = ".intval($parent_id));
    while($rs = mysql_fetch_assoc($sql)) {
        if($parent_id==0) {
            $trees[] = array('id'=>$rs['id'],'name'=>$rs['name']);
        }else {
            $trees[] = array('id'=>$rs['id'],'name'=>$space.$rs['name']);
        }

        $trees = get_cat_tree($rs['id'],$space.'----',$trees);
    }
    return $trees;
}
?>
